<?php

namespace Beerus\Modules\Category\Controllers;

use App\Http\Controllers\Controller;
use Biz\model\brand\Brand as mBrand;
use Biz\service\wiki\AdmWiki;
use Doraemon\model\Category as mCategory;
use Doraemon\model\Spu as mSpu;
use Doraemon\service\Category as sCategory;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CategoryController extends Controller
{
    const SOURCE_CATEGORY_LIST = '/admin/extend/category/child';

    public function index()
    {
        $categories = sCategory::admGetAllCategories();


        $view = view('category::category.index', [
                'categories' => $categories]
        );

        return Admin::content(function (Content $content) use ($view) {
            $content->header('商品分类管理');
            $content->body($view);
        });
    }

    public function edit(Request $request, Content $content, $id = 0)
    {
        $categoryInfo = [];
        $header = '添加分类';
        if ($id) {
            $header = '编辑分类';
            $categoryInfo = sCategory::getCataInfoById4Admin($id);
            if (isset($categoryInfo['father'])) {
                foreach ($categoryInfo['father'] as $item) {
                    switch ($item['deep']) {
                        case 1:
                            $categoryInfo['first_category_id'] = $item['id'];
                            break;
                        case 2:
                            $categoryInfo['second_category_id'] = $item['id'];
                            break;
                        case 3:
                            $categoryInfo['third_category_id'] = $item['id'];
                            break;
                    }
                }
            }
        }
        $topCategory = AdmWiki::admGetChildCategoryMap(0);
        $secondCategory = isset($categoryInfo['first_category_id']) && $categoryInfo['first_category_id'] ? AdmWiki::admGetChildCategoryMap($categoryInfo['first_category_id']) : [];
        $thirdCategory = isset($categoryInfo['second_category_id']) && $categoryInfo['second_category_id'] ? AdmWiki::admGetChildCategoryMap($categoryInfo['second_category_id']) : [];
        $baseForm = new Form($categoryInfo);
        $baseForm->divider('选择父级分类');
        $baseForm->select('first_category_id', '一级类目')->options($topCategory)->load('second_category_id',
            self::SOURCE_CATEGORY_LIST);
        $baseForm->select('second_category_id', '二级类目')->options($secondCategory)->load('third_category_id',
            self::SOURCE_CATEGORY_LIST);
        $baseForm->select('third_category_id', '三级类目')->options($thirdCategory);
        $baseForm->divider('当前分类信息');
        if ($id) {
            $baseForm->text('id', '分类ID')->readonly();
        }
        $baseForm->text('cate_name', '类目名称')->required();
        $baseForm->radio('suggest_status', '是否推荐')->options([0 => '不推荐', 1 => '推荐']);
        $baseForm->text('material', '材质');
        $baseForm->text('size', '尺寸');
        $baseForm->action(url('admin/category/save'));

        return $content
            ->header($header)
            ->description(' ')
            ->breadcrumb(
                ['text' => '商品分类管理', 'url' => '/category'],
                ['text' => $header]
            )
            ->row($baseForm);
    }

    public function info($id = 0)
    {
        $categories = [];
        if ($id != -1) {
            $categories = sCategory::getChildCategory($id);
            $categories = array_map(function ($category) {
                return [
                    "id" => $category["id"],
                    "text" => $category["cate_name"]
                ];
            }, $categories);
        }

        return response()->json($categories);
    }

    public function save(Request $request)
    {
        $id = $request->input('id');
        $postData = $request->all();
        $data = [
            'father_id' => 0,
            'deep' => 1,
            'cate_name' => $postData['cate_name'],
            'suggest_status' => $postData['suggest_status'],
            'material' => $postData['material'],
            'size' => $postData['size'],
        ];
        if ($postData['third_category_id']) {
            $data['father_id'] = $postData['third_category_id'];
            $data['deep'] = 4;
        } else if ($postData['second_category_id']) {
            $data['father_id'] = $postData['second_category_id'];
            $data['deep'] = 3;
        } else if ($postData['first_category_id']) {
            $data['father_id'] = $postData['first_category_id'];
            $data['deep'] = 2;
        }
        $success = new MessageBag([
            'title' => '修改成功'
        ]);
        if (!empty($requestUrl)) {
            return redirect($requestUrl);
        }
        if (!empty($type) && !empty($package_id)) {
            return redirect('/admin/wiki/pack_list?package_id=' . (int)$package_id . $request->getQueryString())->with(compact('success'));
        }
        $title = '添加';
        try {
            if ($id) {
                $title = '编辑';
                $this->updateCataInfoById($id, $data);
            } else {
                $id = mCategory::addCategory($data);
            }
            $success = new MessageBag([
                'title' => $title . '成功'
            ]);
            return redirect('/admin/category')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $title . '失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    private function updateCataInfoById($id, $data)
    {
        $oriCategoryInfo = mCategory::getCataInfoById($id);
        mCategory::updateCataInfoById($id, $data);
        if ($oriCategoryInfo['suggest_status'] != $data['suggest_status']) {
            if ($data['suggest_status'] == mCategory::SUGGEST_STATUS_NOT) {
                mSpu::update(['suggest_status' => mSpu::SUGGEST_STATUS_NOT], [
                    'category_id' => $id,
                    'suggest_sign' => mSpu::SUGGEST_STATUS_NORMAL
                ]);
            } else {
                $suggestBrandIds = mBrand::getBrandIdsBySuggestStatus(mBrand::SUGGEST_STATUS_NORMAL);
                mSpu::update([
                    'suggest_status' => mSpu::SUGGEST_STATUS_ABLE,
                    'suggest_time' => date('Y-m-d H:i:s')
                ], [
                    'brand_id' => $suggestBrandIds,
                    'suggest_sign' => mSpu::SUGGEST_STATUS_NORMAL,
                    'category_id' => $id
                ]);
            }
        }
    }

    public function del(Request $request)
    {
        $categoryId = $request->input("category_id");

        if ($categoryId) {
            $childrenCategoryIds = sCategory::getChildrenListById($categoryId);
            sCategory::deleCataInfoByIds($childrenCategoryIds);
            sCategory::deleCataInfoById($categoryId);
        }

        return response()->json([
            "code" => 0
        ]);
    }

    public function toggle(Request $request)
    {
        $categoryId = $request->input("category_id");
        if ($categoryId) {
            sCategory::toggleCate($categoryId);
        }
        return response()->json([
            "code" => 0
        ]);
    }
}
